package cloud.hedou.abp.asset

import cloud.hedou.abp.remote.HttpClient
import cloud.hedou.abp.remote.HttpClient.Companion.create
import retrofit2.HttpException

class RemoteAssetService(httpClient: HttpClient) {

    private val assetApi: RemoteAssetApi = httpClient.create()

    fun getAsset(assetId: String): Asset {
        if (assetId.isEmpty()) {
            throw IllegalArgumentException("Invalid asset id.")
        }
        val call = assetApi.getAsset(assetId)
        val response = call.execute()
        if (!response.isSuccessful) {
            throw HttpException(response)
        }
        return response.body()!!
    }

    fun setAsset(asset: Asset) {
        val assetId = asset.id
        if (assetId.isNullOrEmpty()) {
            throw IllegalArgumentException("Invalid asset id.")
        }
        val call = assetApi.setAsset(assetId, asset)
        val response = call.execute()
        if (!response.isSuccessful) {
            throw HttpException(response)
        }
    }

    fun assetBorrow(borrowPayload: BorrowPayload) {
        val response = assetApi.assetBorrow(borrowPayload).execute()
        if (!response.isSuccessful) {
            throw HttpException(response)
        }
    }

    fun assetReturn(returnPayload: ReturnPayload) {
        val response = assetApi.assetReturn(returnPayload).execute()
        if (!response.isSuccessful) {
            throw HttpException(response)
        }
    }

}